package com.dacool.activity;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.Window;

import com.dacool.app.sale.R;
import com.dacool.fragment.BaseFragment;
import com.dacool.view.TitleBar;
import com.dacool.view.TitleItem;

public class BaseActivity extends FragmentActivity implements
		FragmentContainerInterface {
	public static final String IntentKeyFullScreen = "customIntent:fullscreen";
	public static final String IntentKeyFragmentClass = "customIntent:fragmentClass";
	public static final String IntentKeyHasTitle = "customIntent:hasTitle";
	public static final String IntentKeyBlockBackButton = "cutomIntent:blockBackButton";

	private MainActivity container;
	private ArrayList<BaseFragment> mFragmentStack;
	private TitleBar mTitleBar;

	public MainActivity getMainActivity() {
		return container;
	}

	public void gotoFragment(Class<? extends BaseFragment> clz) {
		int i = 0;
		for (BaseFragment frag : this.mFragmentStack) {
			if (frag.getClass().equals(clz)) {
				break;
			}
			i++;
		}
//		Log.d("test", "gotoFragment , index:"+i);
		if (i == this.mFragmentStack.size()) {
			try {
				BaseFragment fragment = clz.newInstance();
				this.addFragment(fragment);
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			BaseFragment fragment = mFragmentStack.get(i);
			for (int j = mFragmentStack.size() - 1; j > i; j--) {
				mFragmentStack.remove(j);
			}
			this.addFragment(fragment);
		}
	}

	private boolean blockBackButton = false;

	@Override
	protected void onCreate(Bundle savedInstance) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstance);
		boolean fullscreen = getIntent().getBooleanExtra(IntentKeyFullScreen,
				true);
		boolean hasTitle = getIntent()
				.getBooleanExtra(IntentKeyHasTitle, false);
		mFragmentStack = new ArrayList<BaseFragment>();
		if (fullscreen)
			this.requestWindowFeature(Window.FEATURE_NO_TITLE);// not really
																// full screen ,
																// leave status
																// on
		setContentView(R.layout.frag_container);
		mTitleBar = (TitleBar) findViewById(R.id.titleBar);
		mTitleBar.setBackgroundColor(0xff85c400);
		mTitleBar.setVisibility(hasTitle ? View.VISIBLE : View.GONE);
		blockBackButton = getIntent().getBooleanExtra(IntentKeyBlockBackButton,
				false);
		// getSupportFragmentManager().beginTransaction().disallowAddToBackStack()
		// .commit();
		MainActivity mainActivity = (MainActivity) getIntent()
				.getSerializableExtra("MainActivity");
		if (mainActivity != null)
			this.container = mainActivity;
		try {
			Class clz = (Class) getIntent().getSerializableExtra(
					IntentKeyFragmentClass);
			if (clz != null) {
				BaseFragment frag = (BaseFragment) clz.newInstance();
				this.addFragment(frag);
			}
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public boolean handleBackButton() {
		if (mFragmentStack.size() > 1) {
			BaseFragment frag = mFragmentStack.get(mFragmentStack.size() - 2);
			frag.setStatus(true);
			getSupportFragmentManager().beginTransaction()
					.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
					.replace(R.id.childFragment, frag)
					.commitAllowingStateLoss();
			mFragmentStack.remove(mFragmentStack.size() - 1);
			return true;
		} else
			return false;
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
//		Log.d("test", "onnewIntent");
		super.onNewIntent(intent);
	}

	public void pop(int number) {
		if (number < mFragmentStack.size()) {
			int target = mFragmentStack.size() - 1 - number;
			for (int i = mFragmentStack.size() - 1; i > target; i--) {
				mFragmentStack.remove(i);
			}

			BaseFragment frag = mFragmentStack.get(target);
			frag.setStatus(true);
			getSupportFragmentManager().beginTransaction()
					.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
					.replace(R.id.childFragment, frag)
					.commitAllowingStateLoss();

		}
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onPostCreate(savedInstanceState);
	}

	public void addFragment(BaseFragment fragment) {
		fragment.setStatus(false);
		if (!fragment.isAdded())
			getSupportFragmentManager().beginTransaction()
					.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
					.replace(R.id.childFragment, fragment)
					.commitAllowingStateLoss();
		mFragmentStack.add(fragment);
	}

	public void popToRoot() {
		for (int i = mFragmentStack.size() - 1; i > 0; i--) {
			mFragmentStack.remove(i);
		}
		BaseFragment frag = mFragmentStack.get(0);
		if (frag.isAdded())
			return;
		getSupportFragmentManager().beginTransaction()
				.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
				.replace(R.id.childFragment, frag).commitAllowingStateLoss();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		BaseFragment fragment = mFragmentStack.get(mFragmentStack.size() - 1);
		if (fragment.handleBackButton()) {
			return;
		}
		if (handleBackButton())
			return;
		if (!blockBackButton)
			super.onBackPressed();
		else {
			new AlertDialog.Builder(this).setMessage("确认退出?")
					.setPositiveButton("确认", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
							BaseActivity.this.finish();
							MainActivity.sharedInstance.finish();
						}
					}).setNegativeButton("取消", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub

						}
					}).setCancelable(true).show();
		}
	}

	public TitleItem getTitleView() {
		BaseFragment fragment = mFragmentStack.get(mFragmentStack.size() - 1);
		return fragment.getTitleItem();
		// return null;
	}

	public TitleItem getLeftItem() {
		BaseFragment fragment = mFragmentStack.get(mFragmentStack.size() - 1);
		return fragment.getLeftItem();
		// return null;
	}

	public TitleItem getRightItem() {
		BaseFragment fragment = mFragmentStack.get(mFragmentStack.size() - 1);
		return fragment.getRightItem();
		// return null;
	}

	public TitleItem getSecondLeftItem() {
		BaseFragment fragment = mFragmentStack.get(mFragmentStack.size() - 1);
		return fragment.getSecondLeftItem();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		if (container != null)
			container.onResume(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (container != null) {
			container.onPause(this);
		}
	}

	@Override
	public void onFragmentAttached(BaseFragment a) {
		// TODO Auto-generated method stub
		if (mTitleBar.getVisibility() == View.VISIBLE) {
			mTitleBar.setTitleView(getTitleView());
			mTitleBar.setLeftButton(getLeftItem());
			mTitleBar.setRightButtonItem(getRightItem());
			mTitleBar.setSecondLeftButton(getSecondLeftItem());
		}
		if (container != null) {
			container.activityFragmentChanged(this, a.getStatus());
		}
	}

	@Override
	public void onFragmentRemoved(BaseFragment a) {
		// TODO Auto-generated method stub

	}
	
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		mFragmentStack.clear();
	}
}
